import CryptoJS from 'crypto-js';

// AES加密配置 - 从环境变量获取
const AES_KEY = import.meta.env.VITE_AES_KEY ? CryptoJS.enc.Utf8.parse(import.meta.env.VITE_AES_KEY) : null;
const AES_IV = import.meta.env.VITE_AES_IV ? CryptoJS.enc.Utf8.parse(import.meta.env.VITE_AES_IV) : null;

/**
 * AES加密数据
 */
function encryptData(data: Record<string, any>): { params: string } {
  if (!AES_KEY || !AES_IV) {
    throw new Error('AES加密配置缺失，请检查环境变量 VITE_AES_KEY 和 VITE_AES_IV');
  }

  const srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
  const encrypted = CryptoJS.AES.encrypt(srcs, AES_KEY, {
    iv: AES_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  return {
    params: encrypted.ciphertext.toString().toUpperCase()
  };
}

/**
 * 创建库存助手请求配置
 */
async function createInventoryRequest<T = any>(
  url: string,
  data: Record<string, any>,
  options: {
    encrypt?: boolean;
    addSource?: boolean;
    addPermissions?: boolean;
  } = {}
) {
  const { encrypt = false, addSource = true, addPermissions = true } = options;

  // 添加PC来源标识
  if (addSource) {
    data.source = 'PC';
  }

  // 添加权限信息（从store获取）
  if (addPermissions) {
    // 需要在组件中使用时动态导入，避免循环依赖
    try {
      const { useAuthStore } = await import('@/store/modules/auth');
      const authStore = useAuthStore();
      const rights = authStore.getInventoryRights();

      if (rights) {
        // 通用权限
        data.canSeeCostprice = rights.good?.canSeeCostprice;
        data.selectStocks = rights.stock?.selectStocks;
        data.selectCustoms = rights.custom?.selectCustoms;
        data.seeMyCustom = rights.custom?.seeMyCustom;
        data.seeMyOrder = rights.order?.seeMyOrder;

        // 保持原有的基础权限字段
        // 注：操作权限检查已移至前端，不再需要发送到后端
      }
    } catch {
      // 忽略权限获取失败，使用默认值
    }
  }

  const requestData = encrypt ? encryptData(data) : data;
  const headers: Record<string, string> = {};

  // 添加AES加密标记
  if (encrypt) {
    headers.iscrypto = 'true';
  }

  // 使用全局库存助手请求实例
  const response = await $inventoryRequest<T>({
    url,
    method: 'post',
    data: requestData,
    headers
  });

  return response;
}

// 用户认证相关接口
export namespace InventoryAuth {
  /** 发送验证码 */
  export function sendCode(mobile: string, smsToken: string = '1090637044') {
    return createInventoryRequest<{ token: string }>(
      '/sendCode',
      {
        mobile,
        smsToken
      },
      { encrypt: true }
    );
  }

  /** 手机验证码登录 */
  export function loginByMobileCode(mobile: string, code: string, token: string) {
    return createInventoryRequest<Api.Auth.LoginResult>(
      '/loginByMobileCode',
      {
        mobile,
        code,
        token
      },
      { addPermissions: false }
    ); // 登录接口不添加权限信息
  }

  /** 用户名密码登录 */
  export function loginByUserName(username: string, password: string) {
    return createInventoryRequest<Api.Auth.LoginResult>(
      '/loginByUserName',
      {
        username,
        password
      },
      { addPermissions: false }
    ); // 登录接口不添加权限信息
  }

  /** 获取用户信息 */
  export function getUser() {
    return createInventoryRequest<Api.Auth.UserInfo>('/user/getUser', {});
  }

  /** 更新用户信息 */
  export function updateUser(userData: Record<string, any>) {
    return createInventoryRequest('/user/updateUser', userData);
  }

  /** 忘记密码 */
  export function forgetPwd(mobile: string, code: string, newPassword: string) {
    return createInventoryRequest('/user/forgetPwd', {
      mobile,
      code,
      newPassword
    });
  }

  /** 重置密码 */
  export function resetPassword(oldPassword: string, newPassword: string) {
    return createInventoryRequest('/user/resetPassword', {
      oldPassword,
      newPassword
    });
  }
}

// 报表相关接口
export namespace InventoryReport {
  /** 获取库存报表 */
  export function getStockReport(params: { year: string; month: string; day: string; modlePrice?: string }) {
    return createInventoryRequest('report/stockReport', params);
  }

  /** 获取待办事项 */
  export function getSomethingTodo() {
    return createInventoryRequest('report/stockSometingTodo', {});
  }

  /** 获取出入库图表数据 */
  export function getStockOutInChart(params: { year: string; month: string; day: string; dataType: string }) {
    return createInventoryRequest('report/stockOutInChart', params);
  }

  /** 获取销售图表数据 */
  export function getSellBuyChart(params: { year: string; month: string; day: string; type?: number }) {
    return createInventoryRequest('report/sellPurchaseChart', params);
  }

  /** 获取采购图表数据 */
  export function getPurchaseChart(params: { year: string; month: string; day: string; type?: number }) {
    return createInventoryRequest('report/sellPurchaseChart', params);
  }

  /** 获取仓库库存分布数据 */
  export function getStockNumMoney(params: { year: string; month: string; day: string; dataType: string }) {
    return createInventoryRequest('report/stockGoods', params);
  }

  /** 获取销售分析按商品数据 */
  export function getSellBuyAnaByGood(params: {
    startDate: string;
    endDate: string;
    stock: Record<string, any>;
    typeDesc: string;
    orderDesc: string;
    typeType: number;
  }) {
    return createInventoryRequest('report/sellBuyAna', params);
  }
}

// 员工管理相关接口
export namespace InventoryStaff {
  /** 获取员工列表 */
  export function getStaffList(params: Record<string, any> = {}) {
    return createInventoryRequest('/manage/getStaffList', params);
  }

  /** 保存员工 */
  export function saveStaff(staffData: Record<string, any>) {
    return createInventoryRequest('/manage/saveStaff', staffData);
  }

  /** 删除员工 */
  export function removeStaff(staffId: string) {
    return createInventoryRequest('/manage/removeStaff', { staffId });
  }

  /** 获取员工详情 */
  export function getStaffDetail(staffId: string) {
    return createInventoryRequest('/manage/getStaffDetail', { staffId });
  }

  /** 获取员工角色列表 */
  export function getStaffRoleList(params: Record<string, any> = {}) {
    return createInventoryRequest('/manage/getStaffRoleList', params);
  }

  /** 保存员工角色 */
  export function saveStaffRole(roleData: Record<string, any>) {
    return createInventoryRequest('/manage/saveStaffRole', roleData);
  }

  /** 删除员工角色 */
  export function removeStaffRole(roleId: string) {
    return createInventoryRequest('/manage/removeStaffRole', { roleId });
  }

  /** 获取员工角色详情 */
  export function getStaffRoleDetail(roleId: string) {
    return createInventoryRequest('/manage/getStaffRoleDetail', { roleId });
  }
}

// VIP相关接口
export namespace InventoryVip {
  /** 获取VIP信息 */
  export function getVipInfo() {
    return createInventoryRequest('/user/getVipInfo', {});
  }

  /** 关闭微信通知 */
  export function closeWxNotice() {
    return createInventoryRequest('/user/closeWxNotice', {});
  }
}

// 库存管理相关接口
export namespace InventoryStock {
  /** 获取库存列表 */
  export function getStockList(params: Record<string, any> = {}) {
    return createInventoryRequest('manage/getStockList', params);
  }

  /** 获取默认库存 */
  export function getDefaultStock(params: Record<string, any> = {}) {
    return createInventoryRequest('manage/getDefaultStock', params);
  }

  /** 获取库存详情 */
  export function getStockDetail(params: { stockId?: string } = {}) {
    return createInventoryRequest('manage/getStockDetail', params);
  }

  /** 保存库存 */
  export function saveStock(stockData: Record<string, any>) {
    return createInventoryRequest('manage/saveStock', stockData);
  }

  /** 删除库存 */
  export function removeStock(stockId: string) {
    return createInventoryRequest('manage/removeStock', { stockId });
  }
}

// 商品管理相关接口
export namespace InventoryGoods {
  /** 获取商品列表 */
  export function getGoodsList(params: {
    stockId?: string;
    stockName?: string;
    goodsName?: string;
    productCode?: string;
    packModel?: string;
    position?: string;
    searchText?: string;
    brand?: string;
    goodsClass?: string;
    noReserve?: number;
    productNumber?: string;
    goodCreatedAt?: string;
    order?: string;
    pageNum?: number;
    pageSize?: number;
    modlePrice?: boolean;
    packingUnitPrice?: boolean;
    isStop?: boolean;
    reservePrix?: string;
    reserveNum?: number;
  }) {
    return createInventoryRequest('manage/goodList', params);
  }

  /** 删除商品 */
  export function deleteGood(productId: string) {
    return createInventoryRequest('manage/goodHeaderDel', { productId });
  }

  /** 批量删除商品 (循环调用单个删除) */
  export async function batchDeleteGoods(productIds: string[]) {
    const results = [];

    for (const productId of productIds) {
      try {
        const result = await deleteGood(productId);
        results.push(result);
      } catch (error) {
        results.push({ error: true, message: `删除商品 ${productId} 失败: ${error}` });
      }
    }

    // 返回统一格式的结果
    const hasError = results.some(r => r.error);
    const finalResult = {
      error: hasError,
      data: results,
      message: hasError ? '部分商品删除失败' : '批量删除成功'
    };

    return finalResult;
  }

  /** 置顶商品 (批量接口) */
  export function stickerGood(goodIds: string[]) {
    return createInventoryRequest('manage/goodSticker', { goodIds });
  }

  /** 批量置顶商品 (别名，保持兼容性) */
  export function batchStickerGoods(goodIds: string[]) {
    return stickerGood(goodIds);
  }

  /** 获取商品详情 */
  export function getGoodDetail(goodId: string) {
    return createInventoryRequest('/manage/getGoodDetail', { goodId });
  }

  /** 保存商品 */
  export function saveGood(goodData: Record<string, any>) {
    return createInventoryRequest('/manage/saveGood', goodData);
  }


  /** 获取商品品牌列表 */
  export function getBrandList(
    params: {
      seeRights?: string[] | boolean;
      searchText?: string;
    } = {}
  ) {
    return createInventoryRequest('manage/getBrandList', params);
  }

  /** 保存品牌（新增/编辑） */
  export function saveBrand(
    params: {
      objectId?: string;
      name: string;
      beizhu?: string;
    }
  ) {
    return createInventoryRequest('manage/saveBrand', params);
  }

  /** 删除品牌 */
  export function removeBrand(objectId: string) {
    return createInventoryRequest('manage/removeBrand', { objectId });
  }

  /** 获取商品多图列表 */
  export function getSubGoodIcons(goodId: string) {
    return createInventoryRequest<string[]>('manage/getSubGoodIcons', { goodId });
  }

  /** 商品导入 - 使用FormData上传Excel文件 */
  export function importGoods(formData: FormData) {
    // 使用全局库存助手请求实例，但不使用createInventoryRequest包装
    // 因为文件上传需要特殊的FormData处理
    return $inventoryRequest({
      url: 'common/postExcle',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  /** 下载商品导入模板 */
  export function downloadTemplate(templateType: 'common' | 'morePackunits' | 'morePackModel') {
    const templateMap = {
      common: 'https://api.jimuzhou.top/exlceFile/models/商品通用导入模板.xlsx',
      morePackunits: 'https://api.jimuzhou.top/exlceFile/models/商品多单位导入模板.xlsx',
      morePackModel: 'https://api.jimuzhou.top/exlceFile/models/商品多规格导入模板.xlsx'
    };

    const url = templateMap[templateType];

    // 创建下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = `商品${templateType === 'common' ? '通用' : templateType === 'morePackunits' ? '多单位' : '多规格'}导入模板.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  /** 导出商品（不带图片） */
  export function exportGoods(params: any) {
    return createInventoryRequest('excle/goodExcle', params);
  }

  /** 导出商品（带图片） */
  export function exportGoodsWithImage(params: any) {
    return createInventoryRequest('excle/goodExcleWithImage', params);
  }

  /** 获取商品分类列表 (覆盖原有方法，使用新的参数结构) */
  export function getGoodsClassList(params: { seeRights?: string[] } = {}) {
    return createInventoryRequest('/manage/getGoodClass', params);
  }

  /** 保存商品分类 */
  export function saveGoodsClass(classData: {
    objectId?: string;
    content: string;
    goodClassObjectId?: string;
    classIds?: string[];
  }) {
    return createInventoryRequest('/manage/saveGoodClass', classData);
  }

  /** 删除商品分类 */
  export function removeGoodsClass(objectId: string) {
    return createInventoryRequest('/manage/removeGoodClass', { objectId });
  }

  /** 调整商品分类顺序 (上移/下移) */
  export function upDownGoodsClass(canModify: boolean, moveData: {
    class1: any;
    class2: any;
  }) {
    return createInventoryRequest('/manage/upDownGoodClass', {
      ...moveData,
      canModify
    });
  }

  // ========== 商品套餐相关接口 ==========

  /** 获取商品套餐列表 */
  export function getGoodsZhList(params: {
    stockId?: string;
    stockName?: string;
    goodsName?: string;
    packModel?: string;
    position?: string;
    searchText?: string;
    brand?: string;
    goodsClass?: string;
    noReserveDesc?: string;
    productNumber?: string;
    goodCreatedAt?: string;
    order?: string;
    pageNum?: number;
    pageSize?: number;
    modlePrice?: boolean;
    packingUnitPrice?: boolean;
    isStop?: boolean;
    goodType: 'zhGoods'; // 固定为商品套餐类型
  }) {
    return createInventoryRequest('manage/goodList', params);
  }

  /** 删除商品套餐 */
  export function deleteGoodZh(productId: string) {
    return createInventoryRequest('manage/deletHeaderGood', { productId });
  }

  /** 批量删除商品套餐 (循环调用单个删除) */
  export async function batchDeleteGoodsZh(productIds: string[]) {
    const results = [];

    for (const productId of productIds) {
      try {
        const result = await deleteGoodZh(productId);
        results.push(result);
      } catch (error) {
        results.push({ error: true, message: `删除商品套餐 ${productId} 失败: ${error}` });
      }
    }

    // 返回统一格式的结果
    const hasError = results.some(r => r.error);
    const finalResult = {
      error: hasError,
      data: results,
      message: hasError ? '部分商品套餐删除失败' : '批量删除成功'
    };

    return finalResult;
  }

  /** 置顶商品套餐 (批量接口) */
  export function stickerGoodZh(goodIds: string[]) {
    return createInventoryRequest('manage/goodSticker', { goodIds });
  }

  /** 批量置顶商品套餐 (别名，保持兼容性) */
  export function batchStickerGoodsZh(goodIds: string[]) {
    return stickerGoodZh(goodIds);
  }

  /** 获取商品套餐详情 */
  export function getGoodZhDetail(goodId: string) {
    return createInventoryRequest('/manage/getGoodDetail', { goodId });
  }

  /** 保存商品套餐 */
  export function saveGoodZh(goodData: Record<string, any>) {
    return createInventoryRequest('/manage/saveGood', goodData);
  }
}
